﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MvcShopping.Models;
using System.Data;
using System.Data.Entity;
using System.IO;

namespace MvcShopping.Controllers
{
    public class AdminController : Controller
    {

        MvcShoppingContext1 db = new MvcShoppingContext1();
        //
        // GET: /Admin/
        
        public ActionResult Index()
        {
            var products = db.Products.Include(p => p.productCategory);
            return View(products.ToList());
        }

        //添加商品
        public ActionResult Add()
        {
            //var selectList = new SelectList(db.ProdcutCategories, "Id", "Name");
            //var selectItemList = new List<SelectListItem>();
            //selectItemList.AddRange(selectList);
            //ViewBag.data = selectItemList.AsEnumerable();
            //ViewBag.Id = new SelectList(db.ProdcutCategories, "Id", "Name");

            ViewBag.data= new SelectList(db.ProdcutCategories, "Name", "Name");
            return View();
        }

        [HttpPost]
        public ActionResult Add([Bind(Exclude = "Url")]Product product)
        {
            var chk_product = db.Products.Where(p1 => p1.Name
                == product.Name).FirstOrDefault();
            if (chk_product != null)
            {
                ModelState.AddModelError("Email",
                    "你输入的商品已经存在");

            }
           
                if (Request.Files.Count == 0)
                {
                    throw new Exception("请选择上传文件！");
                }

                string uploadPath = Server.MapPath("../UploadFiles/");


                // 保存文件到UploadFiles文件夹
                //for (int i = 0; i < Request.Files.Count; ++i)
                //{
                HttpPostedFileBase file = Request.Files[0];
                //// 文件名为空证明没有选择上传文件
                //if (file.FileName == "")
                //{
                //    return false;
                //}

                string filePath = uploadPath + Path.GetFileName(file.FileName);
                string fileName = file.FileName;

                //// 检查上传文件的类型是否合法
                //string fileExtension = Path.GetExtension(filePath).ToLower();
                //string fileFilter = ConfigurationManager.AppSettings["FileFilter"];
                //if (fileFilter.IndexOf(fileExtension) <= -1)
                //{
                //    Response.Write("对不起！请上传图片！！");
                //    return false;
                //}

                // 如果服务器上已经存在该文件则要修改文件名与其储存路径
                while (System.IO.File.Exists(filePath))
                {
                    Random rand = new Random();
                    fileName = rand.Next().ToString() + "-" + file.FileName;
                    filePath = uploadPath + Path.GetFileName(fileName);
                }
                // 把文件的存储路径保存起来

                // 保存文件到服务器
                file.SaveAs(filePath);
                // }


                ProductCategory p = db.ProdcutCategories.FirstOrDefault(u => u.Name == product.productCategory.Name);
                //product.productCategory.Id = p.Id;
                product.productCategory = p;
                product.PublishOn = DateTime.Now;
                product.Url = "UploadFiles/" + Path.GetFileName(fileName);
                db.Products.Add(product);
                db.SaveChanges();
                return RedirectToAction("Index");
            
            //return View(product);
        }
            //修改商品信息
            public ActionResult Edit(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            ViewBag.data = new SelectList(db.ProdcutCategories, "Name", "Name");
            return View(product);
        }

        [HttpPost]
        public ActionResult Edit(Product product)
        {
            if (ModelState.IsValid)
            {
                //ProductCategory p = db.ProdcutCategories.FirstOrDefault(u => u.Name == product.productCategory.Name);
                //product.productCategory = p;
                //product.PublishOn = DateTime.Now;
                db.Entry(product).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            return View(product);
        }

        //删除商品
        public ActionResult Delete(int id)
        {
            Product product = db.Products.Find(id);
            if (product == null)
            {
                return HttpNotFound();
            }
            return View(product);
        }

        [HttpPost,ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Product product = db.Products.Find(id);
            db.Products.Remove(product);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            db.Dispose();
            base.Dispose(disposing);
        }


        //订单查看
        public ActionResult AdminOrder()
        {
            return View(db.Orders.ToList());
        }
        public ActionResult AdminDetails(string id)
        {
            var data = (from p in db.OrderDetailItem
                        where p.orderHeader.Id.ToString() == id
                        select p).ToList();

            return View(data);
        }

       
        public void ChangeToAsp(int id) {
            Product product = db.Products.Find(id);
            db.Products.Remove(product);
            db.SaveChanges();
        }
    }
}
